/**
 * 分享页面 - 用于访问分享链接
 */
import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { fileManagerAPI, FileItem } from '@/utils/api';

interface ShareRequestError {
  response?: {
    status?: number;
    data?: {
      error?: string;
      requirePassword?: boolean;
    };
  };
  message?: string;
}

const isShareRequestError = (error: unknown): error is ShareRequestError => {
  if (typeof error !== 'object' || error === null) return false;
  const maybeError = error as ShareRequestError;
  if (maybeError.response !== undefined) {
    if (typeof maybeError.response !== 'object' || maybeError.response === null) {
      return false;
    }
    const { data } = maybeError.response;
    if (data !== undefined && (typeof data !== 'object' || data === null)) {
      return false;
    }
  }
  if (maybeError.message !== undefined && typeof maybeError.message !== 'string') {
    return false;
  }
  return true;
};

const SharePage: React.FC = () => {
  const { shareCode } = useParams<{ shareCode: string }>();
  const navigate = useNavigate();
  const [file, setFile] = useState<FileItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [password, setPassword] = useState('');
  const [requirePassword, setRequirePassword] = useState(false);
  const [passwordError, setPasswordError] = useState('');

  // 加载分享信息
  const loadShareInfo = useCallback(async (pwd?: string) => {
    if (!shareCode) {
      setError('分享码不能为空');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError('');
      setPasswordError('');

      const response = await fileManagerAPI.getShareInfo(shareCode, pwd);
      
      if (response.success && response.data) {
        setFile(response.data);
        setRequirePassword(false);
      } else {
        setError('分享链接不存在或已失效');
      }
    } catch (err: unknown) {
      const defaultMessage = '加载分享信息失败';
      if (isShareRequestError(err)) {
        const status = err.response?.status;
        const errorData = err.response?.data;
        const errorMessage = errorData?.error ?? err.message ?? defaultMessage;
        const needPassword = status === 401 || errorData?.requirePassword;

        if (needPassword) {
          setRequirePassword(true);
          if (pwd) {
            setPasswordError('密码错误，请重新输入');
          }
        } else {
          setError(errorMessage);
        }
      } else {
        setError(defaultMessage);
      }
    } finally {
      setLoading(false);
    }
  }, [shareCode]);

  useEffect(() => {
    // 从URL参数中获取密码
    const urlParams = new URLSearchParams(window.location.search);
    const urlPassword = urlParams.get('password');
    if (urlPassword) {
      setPassword(urlPassword);
      loadShareInfo(urlPassword);
    } else {
      loadShareInfo();
    }
  }, [shareCode, loadShareInfo]);

  // 提交密码
  const handlePasswordSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!password.trim()) {
      setPasswordError('请输入密码');
      return;
    }
    loadShareInfo(password);
  };

  // 下载文件
  const handleDownload = () => {
    if (!shareCode || !file) return;
    
    const downloadUrl = `http://localhost:3000/api/mqz/s/${shareCode}/download${password ? `?password=${encodeURIComponent(password)}` : ''}`;
    window.open(downloadUrl, '_blank');
  };

  // 预览文件
  const handlePreview = () => {
    if (!file) return;
    
    if (file.category === 'image' || file.category === 'video') {
      const previewUrl = `http://localhost:3000${file.url}`;
      window.open(previewUrl, '_blank');
    } else {
      handleDownload();
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (category: string) => {
    const iconMap: Record<string, string> = {
      image: '🖼️',
      video: '🎬',
      audio: '🎵',
      document: '📄',
      other: '📦',
    };
    return iconMap[category] || '📄';
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error && !requirePassword) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-lg shadow-lg max-w-md w-full p-6 text-center">
          <div className="text-6xl mb-4">❌</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">分享链接无效</h1>
          <p className="text-gray-600 mb-6">{error}</p>
          <button
            onClick={() => navigate('/')}
            className="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
          >
            返回首页
          </button>
        </div>
      </div>
    );
  }

  if (requirePassword) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-lg shadow-lg max-w-md w-full p-6">
          <div className="text-center mb-6">
            <div className="text-6xl mb-4">🔒</div>
            <h1 className="text-2xl font-bold text-gray-800 mb-2">需要密码</h1>
            <p className="text-gray-600">此分享链接已设置密码保护</p>
          </div>
          
          <form onSubmit={handlePasswordSubmit}>
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                请输入分享密码
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                  setPasswordError('');
                }}
                className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 ${
                  passwordError ? 'border-red-500 focus:ring-red-500' : 'border-gray-300 focus:ring-blue-500'
                }`}
                placeholder="请输入密码"
                autoFocus
              />
              {passwordError && (
                <p className="mt-1 text-sm text-red-500">{passwordError}</p>
              )}
            </div>
            
            <button
              type="submit"
              className="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              确认
            </button>
          </form>
        </div>
      </div>
    );
  }

  if (!file) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4">
      <div className="max-w-2xl mx-auto">
        {/* 头部 */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-2xl font-bold text-gray-800">文件分享</h1>
            <button
              onClick={() => navigate('/')}
              className="text-gray-500 hover:text-gray-700"
            >
              ✕
            </button>
          </div>
          
          {/* 文件信息卡片 */}
          <div className="border border-gray-200 rounded-lg p-6">
            {/* 文件预览 */}
            <div className="flex items-center gap-6 mb-6">
              <div className="w-24 h-24 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
                {file.category === 'image' && file.url ? (
                  <img
                    src={`http://localhost:3000${file.url}`}
                    alt={file.filename}
                    className="w-full h-full object-cover rounded-lg"
                  />
                ) : file.category === 'video' && file.thumbnailUrl ? (
                  <img
                    src={`http://localhost:3000${file.thumbnailUrl}`}
                    alt={file.filename}
                    className="w-full h-full object-cover rounded-lg"
                  />
                ) : (
                  <span className="text-4xl">{getFileIcon(file.category)}</span>
                )}
              </div>
              
              <div className="flex-1 min-w-0">
                <h2 className="text-xl font-semibold text-gray-800 mb-2 truncate" title={file.filename}>
                  {file.filename}
                </h2>
                <div className="flex flex-wrap gap-4 text-sm text-gray-600">
                  <span>大小: {file.sizeFormatted || formatFileSize(file.size)}</span>
                  <span>类型: {file.category}</span>
                </div>
              </div>
            </div>

            {/* 分享统计 */}
            <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200">
              <div>
                <div className="text-sm text-gray-600">分享下载次数</div>
                <div className="text-lg font-semibold text-gray-800">
                  {file.shareDownloadCount || 0}
                  {file.shareDownloadLimit && ` / ${file.shareDownloadLimit}`}
                </div>
              </div>
              <div>
                <div className="text-sm text-gray-600">过期时间</div>
                <div className="text-lg font-semibold text-gray-800">
                  {file.shareExpireAt
                    ? new Date(file.shareExpireAt).toLocaleString('zh-CN')
                    : '永久有效'}
                </div>
              </div>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-4 mt-6">
            {(file.category === 'image' || file.category === 'video') && (
              <button
                onClick={handlePreview}
                className="flex-1 px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
              >
                {file.category === 'image' ? '预览图片' : '预览视频'}
              </button>
            )}
            <button
              onClick={handleDownload}
              className="flex-1 px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
            >
              下载文件
            </button>
          </div>

          {/* 分享链接信息 */}
          <div className="mt-6 p-4 bg-gray-50 rounded-lg">
            <div className="text-sm text-gray-600 mb-2">分享链接</div>
            <div className="flex items-center gap-2">
              <input
                type="text"
                readOnly
                value={window.location.href}
                className="flex-1 px-3 py-2 bg-white border border-gray-300 rounded text-sm"
              />
              <button
                onClick={() => {
                  navigator.clipboard.writeText(window.location.href);
                  alert('分享链接已复制到剪贴板');
                }}
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 text-sm"
              >
                复制链接
              </button>
            </div>
            <div className="mt-2 text-xs text-gray-500">
              分享码: <span className="font-mono font-semibold">{shareCode}</span>
            </div>
          </div>
        </div>

        {/* 提示信息 */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
          <p className="font-semibold mb-1">💡 提示</p>
          <ul className="list-disc list-inside space-y-1">
            <li>此链接为临时分享链接，请妥善保管</li>
            {file.shareDownloadLimit && (
              <li>下载次数限制: {file.shareDownloadLimit} 次</li>
            )}
            {file.shareExpireAt && (
              <li>过期时间: {new Date(file.shareExpireAt).toLocaleString('zh-CN')}</li>
            )}
          </ul>
        </div>
      </div>
    </div>
  );
};

export default SharePage;

